<?php
namespace app\back\controller;
use Qiniu\Auth;
use think\Controller;
use think\Request;
use think\Db;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager; 
use think\Session;
/*领队活动管理*/
class GuideActivity extends Common
{   
	//活动列表
    public function index()
    {   
    	//获取当前登录的的账号
        $user_name=Session::get('username');
        $user_id=Session::get('userId');
        $userInfo=Db::name('admin')->where(['username'=>$user_name,'id'=>$user_id])->field('uid')->find();
    	  //获取活动已审核数据
    	 $activity = Db::name('activity')->where(['checkId'=>'1','captain_id'=>$userInfo['uid']])->order("id desc")->paginate(5,false);
         $page = $activity->render();
         $this->assign('activity',$activity);
         $this->assign('page',$page);
       return $this->fetch('GuideActivity/index'); 
    }
    //活动添加页面
    public function activity_add()
    {   
      //查询活动分类
      $actype=Db::name('activity_classify')->select();   
       $this->assign('actype',$actype);   
       return $this->fetch('GuideActivity/add'); 
    }
    /*活动发布*/
    public function publish(){
      $data=input('post.');
        //echo 1111111111;die;
    	require_once VENDOR_PATH.'qiniu/php-sdk/autoload.php';
       $arr=input('post.');//获取所有的值
       //获取当前登录的的账号
        $user_name=Session::get('username');
        $user_id=Session::get('userId');
        $res=Db::name('admin')->where(['username'=>$user_name,'id'=>$user_id])->field('uid')->find();
      if(!empty($res['uid'])){
        $rd=Db::name('user_info')->where(['uid'=>$res['uid'],'userFlag'=>'1','member_type'=>'2'])->find();
        if(!empty($rd)){
          $arr['captain_id']=$rd['uid'];
        }
       }
        $file = request()->file('img');
         $arr['createTime']=strtotime($arr['time_from']);//开始时间
         $arr['endTime']=strtotime($arr['time_to']);//结束时间
       // print_r($file);die;
         if($file!==null){           
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            $auth=new Auth();
            // 要上传的空间
            $bucket = "banner";
            //空间域名
            $domain = config('DOMAIN');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return ["err"=>1,"msg"=>$err,"data"=>""];
            }else {
                //返回图片的完整URL
              $arr['goodsThums']=$domain . $ret['key'];
              $data=Db::name('activity')->insertGetId($arr);
              if($data){
               return json(['state' => '1', 'msg' => '发布成功!']);
                }else{
               return json(['state' => '0', 'msg' => '发布失败!']);
                }
            }
        }
    }
    //活动修改页面
    public function edit(){
      $activity_id=input('id');//获取活动id
     $activity=Db::name('activity')->where(['id'=>$activity_id])->find();
     //print_r($activity);die;
     $this->assign('activity',$activity);
      return $this->fetch('GuideActivity/edit'); 
    }
      //活动修改操作
    public function save_activity(){
       $activity_id = input('id');
      //echo $adId;
      $data = input('post.');
      $activity_img = substr(input('goodsThums'),33);
      $file = request()->file('img');
       $data['createTime']=strtotime($data['time_from']);//开始时间
       $data['endTime']=strtotime($data['time_to']);//结束时间
      //echo $file;die;
      if($file==null){
       $data['goodsThums']=$activity_img;
      
        $re=Db::name('activity')->where("id",$activity_id)->update($data);
                if($re){
                   return json(['state' => '1', 'msg' => '删除成功!']);
                 // return  redirect("Activity/index");
                }else{
                   return json(['state' => '1', 'msg' => '删除成功!']);
                 //return redirect("Activity/index");
                }
      }else{
            // 要上传图片的本地路径
            $filePath = $file->getRealPath();
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            require_once VENDOR_PATH.'qiniu/php-sdk/autoload.php';
            // 构建鉴权对象
            $auth = new Auth();
            // 要上传的空间
            $bucket = "banner";
            $domain = config('DOMAIN');//域名
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
             // 初始化 BucketManager 对象并进行文件的删除
            $deleteBuc = new BucketManager($auth);
            // 调用 BucketManager 的 delete 方法进行文件的删除
            $deleteBuc->delete($bucket, $activity_img);
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                return json(['state' => '0', 'msg' => '上传图片失败!']);
            } else {
              $data['goodsThums']=$domain . $ret['key'];
              $re=Db::name('activity')->where("id",$activity_id)->update($data);
              if($re){
               return redirect("Activity/index");
                }else{
                return redirect("Activity/index");
                }
            }
         }
    }
     //单个删除活动
     public function del_activity()
    {
        $aId = input('adid');
      $data = Db::name('activity')->where('id',$aId)->find();
        $activity_img = substr($data['goodsThums'],33);
        if(!empty($activity_img)){
      require_once VENDOR_PATH.'qiniu/php-sdk/autoload.php';
        // 构建鉴权对象
        $auth = new Auth();
         // 要上传的空间
        $bucket ='banner';
         $domain = config('DOMAIN');
        // 初始化 BucketManager 对象并进行文件的删除
        $deleteBuc = new BucketManager($auth);
        // 调用 BucketManager 的 delete 方法进行文件的删除
        list($ret, $err)= $deleteBuc->delete($bucket, $activity_img);
        if($err == null){
            $list = Db::name('activity')->where("id",$aId)->delete();
            if($list){
                 return json(['state' => '1', 'msg' => '删除成功!']);
            }else{
                return json(['state' => '0', 'msg' => '删除失败再试试!']);
            }
        }
      }else{
        $list = Db::name('activity')->where("id",$aId)->delete();
            if($list){
                 return json(['state' => '1', 'msg' => '删除成功!']);
            }else{
                return json(['state' => '0', 'msg' => '删除失败再试试!']);
            }
      }
    
    }
    //活动发布列表
    public function activity_check()
    {   
      //获取banner数据
       $activity = Db::name('activity')->where(['checkId'=>'-1'])->order("id desc")->paginate(5,false);
         $page = $activity->render();
         $this->assign('activity',$activity);
         $this->assign('page',$page);
       return $this->fetch('GuideActivity/activity_check'); 
    }
    
 }   